package jdbc;

import utils.JdbcUtils;
import org.junit.Test;

import java.io.*;
import java.sql.*;

public class ClobDemo {

    @Test
    public void update() throws SQLException, IOException {
        // 初始化资源
        Connection conn = null;
        PreparedStatement ps = null;

        conn = JdbcUtils.getConnection();
        ps = conn.prepareStatement("INSERT into DATA(big_text) VALUES(?) ");

        // 读取文本
        File file = new File("src/jdbc.JdbcDemo.java");
        Reader reader = new BufferedReader(new FileReader(file));

        ps.setCharacterStream(1, reader, file.length());
        ps.executeUpdate();

        // 关闭资源
        reader.close();
        JdbcUtils.free(ps, conn, null);
    }

    @Test
    public void read() throws SQLException, IOException {
        // 初始化
        Connection conn = null;
        PreparedStatement ps = null;
        String sql = "SELECT big_text from DATA ";

        conn = JdbcUtils.getConnection();
        ps = conn.prepareStatement(sql);
        ResultSet rs= ps.executeQuery();

        while (rs.next()) {
            Clob clob = rs.getClob("big_text");
            Reader fr = clob.getCharacterStream(); // 获取输入流

            // 写文件
            Writer fw = new BufferedWriter(new FileWriter("src/JdbcDemo_bake.java"));
            char[] buff = new char[1024];
            for (int i = 0; (i = fr.read(buff))>0;){
                fw.write(buff, 0, i);
            }
            fr.close();
            fw.close();
        }

        // 关闭资源
        JdbcUtils.free(ps, conn, rs);
    }
}
